package net.myspring.middle.service;

import net.myspring.common.mybatis.domain.Page;
import net.myspring.common.mybatis.domain.Pageable;
import net.myspring.common.utils.Collections3;
import net.myspring.middle.domain.Role;
import net.myspring.middle.mapper.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * Created by liuj on 16/7/10.
 */
@Service
public class RoleService {

    @Autowired
    private RoleMapper roleMapper;

    public Page<Role> findPage(Pageable pageable, Map<String, Object> map) {
        return roleMapper.findPage(pageable, map);
    }

    public List<Role> findAll() {
        return roleMapper.findAll();
    }

    public Role findOne(String id) {
        return roleMapper.findOne(id);
    }

    @Transactional
    public Role delete(Role role) {
        role.setEnabled(false);
        roleMapper.update(role);
        return role;
    }

    @Transactional
    public Role save(Role role) {
        boolean isCreate = role.isCreate();
        if (isCreate) {
            roleMapper.save(role);
        } else {
            roleMapper.update(role);
        }
        roleMapper.deletePermissionByRoleId(role.getId());
        if (Collections3.isNotEmpty(role.getPermissionIds())) {
            roleMapper.savePermissions(role.getId(), role.getPermissionIds());
        }
        return role;
    }

    public boolean checkName(Role role) {
        Role checkRole = roleMapper.findByName(role.getName());
        return checkRole == null || checkRole.getId().equals(role.getId());
    }

    public boolean checkCode(Role role) {
        Role checkRole = roleMapper.findByCode(role.getCode());
        return checkRole == null || checkRole.getId().equals(role.getId());
    }

}
